package com.example.mediaservice;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media.MediaBrowserServiceCompat;
import androidx.media.session.MediaButtonReceiver;

import java.util.ArrayList;
import java.util.List;

public class MediaService extends MediaBrowserServiceCompat {
    private static final String TAG = "MediaService";
    private static final String MEDIA_ROOT_ID = "media_root_id";// 媒体根ID

    private MediaSessionCompat mediaSession; // 媒体会话对象
    private NotificationManagerHelper notificationManager;  // 通知管理器对象
    private PlaybackManager playbackManager; // 播放管理器对象
    private List<MediaItem> mediaList; // 媒体列表


    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "MediaService onCreate");

        initMediaList();
        initMediaSession();
        initManagers();

        notificationManager.createNotificationChannel();
        startForeground(notificationManager.getNotificationId(),
                notificationManager.createNotification(playbackManager.isPlaying()));

    }
    private void initMediaList() { // 媒体列表初始化
        mediaList = new ArrayList<>();
        List<MediaItem> localMusic = MediaItem.scanLocalMusic(this);
        if (localMusic.isEmpty()) {
            // 当没有检索到歌曲时，添加示例数据或提示
            mediaList.add(new MediaItem("-1", "未找到本地音乐", "请检查音乐文件", 0));
            Log.d(TAG, "No local music found, using default item");
        } else {
            mediaList.addAll(localMusic);
            Log.d(TAG, "Found " + localMusic.size() + " local music items");
        }
    }

    // 初始化媒体会话对象
    private void initMediaSession() {
        mediaSession = new MediaSessionCompat(this, "MediaService");
        mediaSession.setActive(true); //设置为活跃状态
        mediaSession.setCallback(mediaSessionCallback); // 设置媒体会话回调
        setSessionToken(mediaSession.getSessionToken()); // 设置会话令牌

        // 添加额外信息
        Bundle extras = new Bundle();
        extras.putString("service_info", "音乐服务运行中");
        extras.putBoolean("lyrics_supported", true);
        mediaSession.setExtras(extras);
    }

    // 初始化播放管理器对象
    private void initManagers() {
        // 创建通知管理器对象
        notificationManager = new NotificationManagerHelper(this, mediaSession);
        // 创建播放管理器对象
        playbackManager = new PlaybackManager(mediaSession, mediaList,this);
        // 监听播放状态更新通知栏
        playbackManager.setOnPlaybackUpdateListener(this::updateNotification);
        // 更新媒体元数据
        playbackManager.updateMediaMetadata();
        // 用于更新媒体播放状态
        playbackManager.updatePlaybackState();

    }

    private final MediaSessionCompat.Callback mediaSessionCallback = new MediaSessionCompat.Callback() {
        @Override
        public void onPlay() {
            playbackManager.togglePlayPause(); // 切换播放状态
            playbackManager.updatePlaybackState();
            // 启动前台服务并显示通知
            startForeground(notificationManager.getNotificationId(),
                    notificationManager.createNotification(true));
            updateNotification();

            Bundle extras = new Bundle();
            extras.putBoolean("is_playing", true);
            mediaSession.setExtras(extras);
        }

        @Override
        public void onPause() {
//            playbackManager.setPlaying(false);
            playbackManager.togglePlayPause();
//            playbackManager.updatePlaybackState(playbackManager.getCurrentBarPositionFromState());
            updateNotification();
        }

        @Override
        public void onSkipToNext() {
            playbackManager.skipToNext();
//            playbackManager.updatePlaybackState();
            updateNotification();
        }

        @Override
        public void onSkipToPrevious() {
            playbackManager.skipToPrevious();
//            playbackManager.updatePlaybackState();
            updateNotification();
        }

        @Override
        public void onSeekTo(long pos) {
            Log.d(TAG, "onSeekTo called with position: " + pos);
            playbackManager.seekTo(pos);
            playbackManager.updatePlaybackState(pos);
            updateNotification();
        }
    };


    // 该方法根据当前播放状态创建并显示通知，用于在通知栏显示播放控制信息
    private void updateNotification() {
        Notification notification = notificationManager.createNotification(playbackManager.isPlaying());
        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager != null) {
            manager.notify(notificationManager.getNotificationId(), notification);
        }
    }

    // 当服务启动时调用此方法处理媒体按钮事件
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "MediaService onStartCommand");
//        MediaButtonReceiver.handleIntent(mediaSession, intent);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (mediaSession != null) {
            mediaSession.release();
        }
        if (playbackManager != null) {
            playbackManager.release(); // 释放MediaPlayer
        }
        stopForeground(true);
        super.onDestroy();
    }


    @Nullable
    @Override
    public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) {
        Log.d(TAG, "Client connecting: " + clientPackageName);
        return new BrowserRoot(MEDIA_ROOT_ID, null);
    }

    @Override
    public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
        Log.d(TAG, "onLoadChildren called with parentId: " + parentId);
        result.sendResult(new ArrayList<>());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

}
